import {
  addAddress,
  getAddress,
  updateAddress
} from "../../utils/api";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    userName:'',
    phone:'',
    area:'',
    address:'',
    addressList:[],
    type:'',
    id:''
  },


  backHome: function () {
    
  },

  saveAddress(){
    this.saveAdd()
  },

  async saveAdd() {
    if(this.data.type==='update'){
      console.log('判断成功')
      const res = await updateAddress(this.data.id,this.data.userName, this.data.phone,this.data.area,this.data.address)
      this.setData({
        show:false
      })
      this.getAddress()
      return
    }
    const res = await addAddress(this.data.userName, this.data.phone,this.data.area,this.data.address)
    if (res.code === 200) {
      this.setData({
        show:false
      })
    }
    this.getAddress()
  },

  async getAddress() {
    const res = await getAddress()
       console.log(res)
      this.setData({
        addressList:res.data
      })
      console.log(this.data.addressList)
  },

  editAddress(e){
    this.setData({
      id:e.currentTarget.dataset.id,
      userName:e.currentTarget.dataset.name,
      phone:e.currentTarget.dataset.phone,
      area:e.currentTarget.dataset.area,
      address:e.currentTarget.dataset.address,
      type:'update',
      show:true
    })
  },

  /**添加地址 */
  saveAdderssList(){
    this.setData({
      type:'add',
      show:true
    })
  },
  back: function () {
    wx.navigateBack({
      delta: 1
    })
  },

  bindName(e){
    this.setData({
      userName:e.detail.value
    })
  },
  bindPhone(e){
    this.setData({
      phone:e.detail.value
    })
  },
  bindArea(e){
    this.setData({
      area:e.detail.value
    })
  },
  bindAddress(e){
    this.setData({
      address:e.detail.value
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getAddress()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
   
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})